/**
 * @(#) ForeignTradeAcquisition.java
 *
 * @author lihg
 * @version V1.0 2013-10-8
 *
 * Copyright (C) 2010,2013 , Lihg
 */

/**
 * 
 */
package cn.com.dshome.acquisition.service.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import cn.com.dshome.acquisition.exception.AcquisitionException;
import cn.com.dshome.acquisition.service.Acquisition;
import cn.com.dshome.acquisition.utils.HttpClientUtils;
import cn.com.dshome.acquisition.utils.StringUtils;
import cn.com.dshome.acquisition.vo.BaseInformation;

/**
 * 
 * Purpose:
 * 
 * @author lihg
 * @see
 * @since
 */
@Service("fta")
public class ForeignTradeAcquisition implements Acquisition {

	private static final long serialVersionUID = 7688391197380338331L;

	//记录日志
	private Log log = LogFactory.getLog(ForeignTradeAcquisition.class) ;

	@Autowired
	@Qualifier("httpClientUtils")
	private HttpClientUtils hcu ;

	private String URI = "http://www.waimaoqiye.com" ;

	@Autowired
	private TaskExecutor taskExecutor ;

	/* (non-Javadoc)
	 * @see cn.com.dshome.acquisition.service.Acquisition#listInformation(java.lang.Class)
	 */
	@Override
	public <T extends BaseInformation> List<T> listInformation(Class<T> clazz)
	throws AcquisitionException {
		String responseMessage = convertByteToString(hcu.getResponseMessage(URI)) ;
		Document document = Jsoup.parse(responseMessage) ;
		Elements areas = document.select("ul.classmenubar>li>a") ;
		for(final Element area : areas){
			//			taskExecutor.execute(new Runnable() {
			//				@Override
			//				public void run() {
			String areaUrl = URI + area.attr("href") ;
			try {
				fetchDetailsMessage(areaUrl) ;
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
			} catch (AcquisitionException e) {
				e.printStackTrace();
			}
			//				}
			//			}) ;

		}
		return null;
	}

	private void fetchDetailsMessage(String areaUrl) throws AcquisitionException{
		String responseMessage = convertByteToString(hcu.getResponseMessage(areaUrl)) ;
		Document document = Jsoup.parse(responseMessage) ;
		Elements companies = document.select("table.tablist td.shoplistrow ul>a") ;
		for(final Element company : companies){
			taskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					log.error(company.text()) ;
				}
			}) ;
		}
		//获取总页
		Element totalPage = document.select("td[title=页次]").first() ;
		if(null != totalPage){
			String sta = totalPage.text() ;
			sta = sta.trim() ;
			//总页
			Integer pageCount =  Integer.valueOf(sta.substring(sta.indexOf("/") + 1,sta.length() - 2)) ;
			//获取当前页
			Integer now = Integer.valueOf(document.select("td.tablebody2>font.normalTextSmall>u>b").first().text()) ;
			System.out.println("当前页："  + now + "\t共：" + pageCount + "\t URL" + areaUrl );
			if(now <= pageCount){
				now += 1 ;
			}else{
				return ;
			}
			//获取下一页URL
			String nextUrl = areaUrl.replaceAll("(.*?)(\\d+\\.html)","$1") + now + ".html" ;
			fetchDetailsMessage(nextUrl) ;
		}
	}

	/**
	 * Byte转String
	 * @param content
	 * @return
	 */
	private String convertByteToString(byte[] content){
		try {
			String charSet = hcu.getChartSet() ;
			if (StringUtils.hasLength(charSet)) {
				return StringUtils.byteArray2String(content, charSet);
			} else {
				return StringUtils.byteArray2String(content);
			}
		} catch (Exception e) {
			log.error("convertByteToString failed " ,e) ;
			return null ;
		}
	}

	public static void main(String[] args) throws AcquisitionException {
		ForeignTradeAcquisition fta = new ForeignTradeAcquisition() ;
		fta.listInformation(null) ;
	}
}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2013-10-8 下午11:11:33 lihg 创建版本
 */